<template>
  <view class="order-detail-page">
    <!-- 商品信息区域 -->
    <view class="product-section">
      <view class="product-list">
        <view
          class="product-item"
          v-for="product in displayProducts"
          :key="product.id"
        >
          <view class="product-image">
            <image :src="product.listImg" mode="aspectFit"></image>
          </view>
          <view class="product-info">
            <view class="product-name">{{ product.name }}</view>
            <view class="stock-info">共{{ product.quantity }}件</view>
            <view class="product-price">{{ product.price }}</view>
          </view>
        </view>
      </view>
      <view class="expand-more" @click="toggleExpand" v-if="remainingCount > 0">
        <text>{{
          isExpanded ? "收起商品" : `展开剩余商品(${remainingCount}件)`
        }}</text>
        <view class="arrow" :class="{ expanded: isExpanded }">
          <image
            src="https://jyoungy.oss-cn-beijing.aliyuncs.com/jyy-mini-sale/order/arrow.png"
            mode="widthFix"
          ></image>
        </view>
      </view>
    </view>

    <!-- 收货地址区域 -->
    <view class="address-section">
      <view class="section-header">
        <view class="location-icon">
          <image
            src="https://jyoungy.oss-cn-beijing.aliyuncs.com/jyy-mini-sale/order/address.png"
            mode="widthFix"
          ></image>
        </view>
        <text class="section-title">收货地址</text>
        <view class="edit-btn" @click="editAddress">
          <text>{{
            orderData.recipient.telNumber ? "编辑" : "导入微信地址"
          }}</text>
          <image
            :src=" orderData.recipient.telNumber ? 'https://jyoungy.oss-cn-beijing.aliyuncs.com/jyy-mini-sale/order/edit.png' : 'https://jyoungy.oss-cn-beijing.aliyuncs.com/jyy-mini-sale/order/wechatlogo.png'"
            mode="widthFix"
          ></image>
        </view>
      </view>
      <view class="address-content" v-if="orderData.recipient.telNumber">
        <view class="recipient-info"
          >{{ orderData.recipient.userName }}
          {{ orderData.recipient.telNumber }}</view
        >
        <view class="address-detail"
          >{{ orderData.recipient.provinceName
          }}{{ orderData.recipient.cityName }}{{ orderData.recipient.countyName
          }}{{ orderData.recipient.detailInfo }}</view
        >
      </view>
    </view>

    <!-- 发货时间区域 -->
    <view class="delivery-section">
      <view class="section-header" :class="{ 'border-bottom': needInvoice }">
        <view class="truck-icon">
          <image
            src="https://jyoungy.oss-cn-beijing.aliyuncs.com/jyy-mini-sale/order/car.png"
            mode="widthFix"
          ></image>
        </view>
        <text class="section-title">发货时间</text>
        <view class="delivery-time">
          <text>订单支付后</text>
          <text>预计24小时内发货</text>
        </view>
      </view>
    </view>

    <!-- 发票区域 -->
    <view class="invoice-section" v-if="userInfo.type === 3">
      <view class="section-header">
        <view class="invoice-icon">
          <image
            src="https://jyoungy.oss-cn-beijing.aliyuncs.com/jyy-mini-sale/icons/invoice.png"
            mode="widthFix"
          ></image>
        </view>
        <text class="section-title">发票</text>
        <view class="invoice-status" @click="showInvoiceModal">
          <text>{{ needInvoice ? "需要发票" : "不需要发票" }}</text>
          <image
            src="https://jyoungy.oss-cn-beijing.aliyuncs.com/jyy-mini-sale/icons/arrow-rignt.png"
            mode="widthFix"
          ></image>
        </view>
      </view>
    </view>

    <!-- 发票弹窗 -->
    <uni-popup
      ref="invoicePopup"
      type="bottom"
      background-color="#ffffff"
      border-radius="24rpx 24rpx 0 0"
    >
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">开具电子发票</text>
          <view class="close-btn" @click="hideInvoiceModal">
            <text>✕</text>
          </view>
        </view>

        <view class="modal-body">
          <view class="modal-desc"
            >当您的订单完成后，我们会将电子发票发送至您在下方所预留的邮箱地址。如有任何疑问，您可以联系我们的在线顾问进行咨询。</view
          >

          <view class="form-item">
            <text class="form-label">电子邮箱</text>
            <input
              class="form-input"
              v-model="invoiceData.email"
              type="email"
              :class="{ error: emailError }"
              placeholder="请填写"
            />
            <text class="error-text" v-if="emailError">请输入您的电子邮箱</text>
          </view>

          <view class="form-item">
            <radio-group @change="onInvoiceTypeChange">
              <view class="invoice-type">
                <label class="type-option">
                  <radio
                    value="personal"
                    :checked="invoiceData.type === 'personal'"
                    color="#000"
                  />
                  <text>个人</text>
                </label>
                <label class="type-option">
                  <radio
                    value="company"
                    :checked="invoiceData.type === 'company'"
                    color="#000"
                  />
                  <text>公司</text>
                </label>
              </view>
            </radio-group>
          </view>

          <view class="form-item" v-if="invoiceData.type === 'company'">
            <view class="form-label">
              公司名称
              <view @click="invoiceAuth" class="form-auth"
                >授权发票信息<image
                  src="https://jyoungy.oss-cn-beijing.aliyuncs.com/jyy-mini-sale/icons/arrow-rignt.png"
                  mode="widthFix"
                ></image>
              </view>
            </view>
            <input
              class="form-input"
              v-model="invoiceData.companyName"
              placeholder="请填写"
            />
          </view>

          <view class="form-item" v-if="invoiceData.type === 'company'">
            <text class="form-label">纳税人识别号/统一社会信息代码</text>
            <input
              class="form-input"
              v-model="invoiceData.taxNumber"
              placeholder="请填写"
            />
          </view>

          <button class="save-btn" @click="saveInvoiceInfo">保存</button>
        </view>
      </view>
    </uni-popup>

    <!-- 底部操作区域 -->
    <view class="bottom-section">
      <view class="privacy-agreement">
        <radio-group @change="radioChange">
          <label>
            <radio
              :checked="agreedToTerms"
              color="#000"
              style="transform: scale(0.5)"
            />
            <text>提交订单即表表明您接受我们的</text>
            <text class="link" @click="showPrivacyPolicy">隐私政策</text>
            <text>和</text>
            <text class="link" @click="showSalesTerms">销售条款</text>
          </label>
        </radio-group>
      </view>
      <view class="order-footer">
        <view class="total-price">
          <text
            ><text class="text-1">总价：</text
            ><text class="text-2">{{ totalPrice }}</text></text
          >
        </view>
        <button
          class="submit-btn"
          @click="submitOrder"
          :disabled="!agreedToTerms"
        >
          <text>{{ userInfo.type === 3 ? "支付" : "提交订单" }}</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import orderApi from "@/request/order";
import authManager from "@/utils/auth";
export default {
  data() {
    return {
      userInfo: {},
      type: 1, // 下单来源
      isExpanded: false,
      agreedToTerms: false,
      needInvoice: false,
      emailError: false,
      productId: "",
      invoiceData: {
        email: "",
        type: "personal", // personal 或 company
        companyName: "",
        taxNumber: "",
      },
      orderData: {
        products: [],
        recipient: {},
      },
    };
  },
  computed: {
    // 显示的商品列表
    displayProducts() {
      if (this.isExpanded) {
        return this.orderData.products;
      } else {
        return this.orderData.products.slice(0, 1);
      }
    },
    // 剩余商品数量
    remainingCount() {
      const remaining = this.orderData.products.length - 1;
      return remaining > 0 ? remaining : 0;
    },
    // 总价计算
    totalPrice() {
      return this.orderData.products.reduce(
        (total, product) => total + product.price * (product.quantity || 1),
        0
      );
    },
  },
  onLoad(options) {
    this.userInfo = authManager.getUserInfo();

    // 商品详情下单
    if (options.productStr) {
      this.type = 1;
      this.orderData.products = [
        JSON.parse(decodeURIComponent(options.productStr)),
      ];
    }

    // 购物车多商品下单
    if (options.productsStr) {
      this.type = 2;
      this.orderData.products = JSON.parse(
        decodeURIComponent(options.productsStr)
      );
    }

    const address = uni.getStorageSync("address");
    if (address) {
      this.orderData.recipient = JSON.parse(address);
    }
  },
  methods: {
    toggleExpand() {
      // 添加触觉反馈
      uni.vibrateShort({
        type: "light",
      });

      this.isExpanded = !this.isExpanded;
    },
    editAddress() {
      const that = this;
      uni.chooseAddress({
        success(res) {
          console.log(res);
          // 地址本地缓存
          that.orderData.recipient = { ...res };
          uni.setStorageSync("address", JSON.stringify(res));
        },
        fail(e) {
          console.log("e :>> ", e);
        },
      });
    },
    showInvoiceModal() {
      this.$refs.invoicePopup.open();
    },
    hideInvoiceModal() {
      this.$refs.invoicePopup.close();
      this.emailError = false;
    },
    onInvoiceTypeChange(e) {
      this.invoiceData.type = e.detail.value;
      if (this.invoiceData.type === "personal") {
        this.invoiceData.companyName = "";
        this.invoiceData.taxNumber = "";
      }
    },
    invoiceAuth() {
      const that = this;
      uni.chooseInvoiceTitle({
        success(res) {
          if (res.type === "0") {
            that.invoiceData.type = "company";
          } else {
            that.invoiceData.type = "personal";
          }
          if (res.type === "0") {
            that.invoiceData.companyName = res.title;
            that.invoiceData.taxNumber = res.taxNumber;
          } else {
            that.invoiceData.companyName = "";
            that.invoiceData.taxNumber = "";
          }
        },
      });
    },
    saveInvoiceInfo() {
      // 验证邮箱
      if (!this.invoiceData.email) {
        this.emailError = true;
        return;
      }

      // 验证邮箱格式
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(this.invoiceData.email)) {
        this.emailError = true;
        return;
      }

      this.emailError = false;
      this.needInvoice = true;
      this.hideInvoiceModal();

      uni.showToast({
        title: "发票信息保存成功",
        icon: "success",
      });
    },
    radioChange(e) {
      this.agreedToTerms = e;
    },
    showPrivacyPolicy() {
      uni.showToast({
        title: "查看隐私政策",
        icon: "none",
      });
    },
    showSalesTerms() {
      uni.showToast({
        title: "查看销售条款",
        icon: "none",
      });
    },
    submitOrder() {
      if (!this.agreedToTerms) {
        uni.showToast({
          title: "请先同意隐私政策和销售条款",
          icon: "none",
        });
        return;
      }

      const goods = this.orderData.products.map((x) => {
        return {
          goodsId: x.id,
          quantity: x.quantity,
        };
      });

      uni.showLoading({
        title: "正在提交订单...",
      });
      const data = {
        type: this.type,
        goods,
      };
      orderApi
        .createOrder(data)
        .then((res) => {
          if (this.userInfo.type !== 3) {
            const da = {
              orderId: res.orderId,
              invoiceType: 0,
              name: this.orderData.recipient.userName,
              phone: this.orderData.recipient.telNumber,
              address: `${this.orderData.recipient.provinceName} ${this.orderData.recipient.cityName} ${this.orderData.recipient.detailInfo}`,
            };
            orderApi
              .payOrder(da)
              .then((r) => {
                uni.hideLoading();

                // 跳转到订单完成页面
                uni.redirectTo({
                  url: `/pages/order/finish?result=${r.payResult}&orderId=${res.orderId}&totalPrice=${this.totalPrice}`,
                });
              })
              .catch((err) => {
                uni.hideLoading();
                uni.showToast({
                  title: err.message || "支付失败",
                  icon: "none",
                });
              });
          } else {
			const paydata = {
              orderId: res.orderId,
              invoiceType: this.needInvoice ? this.invoiceData.type === "company" ? 2 : 1 : 0,
              name: this.orderData.recipient.userName,
              phone: this.orderData.recipient.telNumber,
              address: `${this.orderData.recipient.provinceName} ${this.orderData.recipient.cityName} ${this.orderData.recipient.detailInfo}`,
              email: this.invoiceData.email,
              companyName: this.invoiceData.companyName,
              taxNumber: this.invoiceData.taxNumber,
            };
			uni.setStorageSync(`paydata_${res.orderId}`, JSON.stringify(paydata));
			uni.redirectTo({
				url: `/pages/order/pay?orderId=${res.orderId}&amount=${this.totalPrice}`,
			});
          }
        })
        .catch((err) => {
          uni.hideLoading();
          uni.showToast({
            title: err.message || "订单提交失败",
            icon: "none",
          });
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.order-detail-page {
  background-color: #fff;
  min-height: 100vh;
  padding-bottom: 140rpx;
}

.product-section {
  background-color: #ffffff;
  margin-bottom: 20rpx;
  padding: 30rpx;
}

.product-list {
  margin-bottom: 20rpx;
}

.product-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 30rpx;
  opacity: 1;
  transform: translateY(0);
  transition: all 0.3s ease;

  &:last-child {
    margin-bottom: 0;
  }
}

.product-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 0;
  overflow: hidden;
  margin-right: 20rpx;

  image {
    width: 100%;
    height: 100%;
    background-color: #f0f0f0;
  }
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 26rpx;
  font-weight: 500;
  color: #333333;
  margin-bottom: 10rpx;
  line-height: 1.4;
}

.stock-info {
  font-size: 22rpx;
  color: #999999;
  margin-bottom: 15rpx;
  line-height: 1.4;
}

.product-price {
  font-size: 32rpx;
  font-weight: 600;
  color: #010101;

  &::before {
    content: "￥";
    font-size: 20rpx;
  }
}

.expand-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #f0f0f0;
  border: 1rpx solid #e0e0e0;
  border-radius: 0;
  background-color: #ffffff;
  color: #666666;
  font-size: 22rpx;
  margin-top: 20rpx;

  .arrow {
    margin-left: 10rpx;
    transition: transform 0.3s ease;

    &.expanded {
      transform: rotate(180deg);
    }

    image {
      width: 13rpx;
    }
  }
}

.address-section,
.delivery-section,
.invoice-section {
  background-color: #ffffff;
  margin-bottom: 20rpx;
  padding: 30rpx 60rpx;
  padding-bottom: 0;
}

.section-header {
  display: flex;
  align-items: center;
  padding-bottom: 40rpx;
}

.border-bottom {
  border-bottom: 1rpx solid #cbcbcb;
}

.location-icon,
.truck-icon,
.invoice-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 15rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  image {
    width: 26rpx;
  }
}

.truck-icon {
  image {
    width: 41rpx;
  }
}

.section-title {
  flex: 1;
  font-size: 28rpx;
  font-weight: 500;
  color: #000;
}

.edit-btn {
  display: flex;
  align-items: center;
  color: #666666;
  font-size: 22rpx;

  image {
    margin-left: 11rpx;
    width: 26rpx;
  }
}

.invoice-status {
  display: flex;
  align-items: center;
  color: #666666;
  font-size: 22rpx;

  image {
    margin-left: 11rpx;
    width: 8rpx;
  }
}

.address-content {
  padding-bottom: 60rpx;
  border-bottom: 1rpx solid #cbcbcb;
}

.recipient-info {
  font-size: 28rpx;
  color: #666666;
  margin-bottom: 20rpx;
}

.address-detail {
  font-size: 28rpx;
  color: #666666;
}

.delivery-time {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  font-size: 22rpx;
  color: #666666;
  line-height: 1.3;
}

// uni-popup 发票弹窗样式
.modal-content {
  width: 100%;
  background-color: #ffffff;
  border-radius: 24rpx 24rpx 0 0;
  padding-bottom: 55rpx;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30rpx 30rpx 0 30rpx;
  margin-bottom: 30rpx;
  position: relative;
}

.modal-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #000;
}

.close-btn {
  position: absolute;
  right: 30rpx;
  top: 30rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  color: #666;
}

.modal-body {
  padding: 0 60rpx;
}

.modal-desc {
  font-size: 26rpx;
  color: #000000;
  line-height: 42rpx;
  margin-bottom: 56rpx;
}

.form-item {
  margin-bottom: 40rpx;
}

.form-label {
  display: block;
  font-size: 24rpx;
  color: #000;
  margin-bottom: 18rpx;
  .form-auth {
    float: right;
    font-size: 24rpx;
    color: #818181;
    image {
      width: 8rpx;
      margin-left: 10rpx;
      vertical-align: middle;
    }
  }
}

.form-input {
  width: 100%;
  height: 80rpx;
  padding: 0 20rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
  border: none;

  &::placeholder {
    color: #999;
  }

  &.error {
    border: 1.5rpx solid #9a102d;
    background-color: #f5dbdc;
  }
}

.error-text {
  font-size: 24rpx;
  color: #9a102d;
  margin-top: 10rpx;
  display: block;
}

.invoice-type {
  display: flex;
  gap: 60rpx;
}

.type-option {
  display: flex;
  align-items: center;

  radio {
    margin-right: 20rpx;
    transform: scale(0.6);
  }

  text {
    font-size: 26rpx;
    color: #000;
  }
}

.save-btn {
  width: 100%;
  height: 88rpx;
  background-color: #000;
  color: #fff;
  border-radius: 0;
  font-size: 32rpx;
  border: none;
  margin-top: 88rpx;
}

.bottom-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  border-top: 1rpx solid #f0f0f0;
  z-index: 10;
}

.privacy-agreement {
  padding: 20rpx 30rpx;
  font-size: 24rpx;
  color: #000;

  label {
    display: flex;
    align-items: center;
  }

  checkbox {
    margin-right: 10rpx;
  }

  .link {
    text-decoration: underline;
  }
}

.order-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
}

.total-price {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;

  .text-1 {
    font-size: 22rpx;
  }

  .text-2 {
    font-size: 40rpx;
    color: #010101;

    &::before {
      content: "￥";
      font-size: 28rpx;
    }
  }
}

.submit-btn {
  background-color: #000000;
  color: #ffffff;
  border-radius: 0;
  padding: 0 60rpx;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 32rpx;
  border: none;
  margin: 0;

  &:disabled {
    background-color: #cccccc;
    color: #999999;
  }
}

// 字体图标样式
.iconfont {
  font-family: "iconfont";
}
</style>
